<?php
/*
    OpenLib
    Copyright (C) 2011  Michael Gukov, Pham Thi Thuy Duong

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/


namespace Sun;

require_once dirname(__FILE__).'/sunloader.php';

class Sun {
    private static $app;
    private static $conf;
    private static $app_path;

    public static $swap;
    public static $db;

    private function __construct() { }

    public static function app() {
        return self::$app;
    }
    public static function conf($path) {
        $i = explode('/', $path);
        return self::$conf[$i[0]][$i[1]];
    }

    public static function appPath() {
        return self::$app_path;
    }

    public static function createLoader() {
        AutoLoader::registerLoader();
        new SunLoader();
        new AppLoader();
    }

    public static function setAppConfig($conf) {
        self::$conf = $conf;
    }

    public static function setAppPath($app_path) {
        self::$app_path = $app_path;
    }

    public static function runApplication($app) {
        self::$app = $app;
        self::$app->Run();
    }

    private static function produce($class, $need_param, $param, $type, $name) {
        try {
            if (isset($param) || $need_param) return new $class($param);
            return new $class();
        } catch (Exceptions\NotFound $e) {
            throw new Exceptions\NotFound($type, $name);
        }
    }

    public static function view($name, $param = null, $need_param = 0) {
        return self::produce("\\App\\Views\\".$name,
            $need_param, $param, "View", $name);
    }
    public static function model($name, $param = null, $need_param = 0) {
        return self::produce("\\App\\Models\\".$name,
            $need_param, $param, "Model", $name);
    }
    public static function validator($name, $param = null, $need_param = 0) {
        return self::produce("\\App\\Validators\\".$name,
            $need_param, $param, "Validator", $name);
    }
    public static function controller($name, $param = null, $need_param = 0) {
        return self::produce("\\App\\Controllers\\".$name,
            $need_param, $param, "Controller", $name);
    }
}
